import json
import sys

from services.ZhangTingService import ZhangTingService

sys.path.append("../../")

from model.StockBaseInfo import *
from model.CommonDb import *
from services.CodesService import *
from services.DayKlineService import *
from frameworks.utils.RedisUtil import *
from prettytable import PrettyTable
import datetime
import numpy as np

class TaskController:
    def __init__(self,args):
        self.args = args
        self.service = StockBaseInfo()
        self.codeService = CodeService()
        self.klineService = DayKlineService()
        self.today = datetime.datetime.now().strftime("%Y-%m-%d")
        self.zhangtingservice = ZhangTingService()
    def run(self):
        if self.args["func"] == "parseStock":
            return self.parseStock(self.args)

    """
    添加总体评论
    """
    def parseStock(self,args):
        codes = self.zhangtingservice.getZhangtingInfo(1)
        redis = RedisUtil()
        m = 0
        tb = PrettyTable()
        tb.field_names = ['code', 'codename', 'money', 'zhangfu', 'rednum',"zhengfu"]
        for row in codes:
            datas = {}
            code = row["code"]
            klineday = self.klineService.getData(code)
            key = "kline_data_" + str(code)
            al = redis.vget(key)            
            if al == None:
                print("=================set cache=======================")
                al = json.dumps(klineday)
                redis.vset(key, al)
            else:
                print("=======read cache===============")
                #print(al)
            klineday = json.loads(al)
            rednum = 0
            for keyindex in range(len(klineday)):
                klineday[keyindex]["codename"] = row["codename"]
                if klineday[keyindex]["pre_close"] != None:
                    klineday[keyindex]["zhangfu"] = round(
                        (float(klineday[keyindex]["close"])-float(klineday[keyindex]["pre_close"]))*100/float(klineday[keyindex]["pre_close"])
                         ,2)
                else:
                    klineday[keyindex]["zhangfu"] = 0.00
                if klineday[keyindex]["zhangfu"] < 0:
                    rednum = 0
                else:
                    rednum += 1
                klineday[keyindex]["rednum"] = rednum
                klineday[keyindex]["zhengfu"] = round(
                    (float(klineday[keyindex]["high"]) - float(klineday[keyindex]["low"])) * 100 / float(
                        klineday[keyindex]["low"])
                    , 2)
            newdfdata = pd.DataFrame(klineday)
            """
            ma_list = [5, 10, 20]
            for ma in ma_list:
                newdfdata['close_ma_' + str(ma)] = newdfdata["close"].rolling(ma).mean()
            for ma in ma_list:
                newdfdata['volume_ma_' + str(ma)] = newdfdata["volume"].rolling(ma).mean()
            ma_list = [3, 5, 10]
            for ma in ma_list:
                newdfdata['zhengfu_ma_' + str(ma)] = newdfdata["zhengfu"].rolling(ma).mean()
            """
            newdfdata.set_index("trade_date", inplace=True)
            lastrow = np.array(newdfdata[-1:])
            option = lastrow[0]
            tb.add_row([option[1],option[15],round(row["flow_money"]/100000000,2), option[16], option[17],option[18]])
            m += 1
        print(tb.get_string(sortby="rednum", reversesort=True))


